package com.wx.elasticsearch.elasticsearch.controller;

import com.wx.elasticsearch.elasticsearch.dao.BookDao;
import com.wx.elasticsearch.elasticsearch.entity.Book;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @author wx
 * @Description:
 * @date 2019/3/8 000812:16
 */
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookDao bookDao;


    /**
     * @description: 根据文档id查询
     * @author: wx
     * @date: 2019/3/8 0008
     * @param id
     * @return: com.wx.elasticsearch.elasticsearch.entity.Book
     */
    @GetMapping("/get/{id}")
    public Book getBookById(@PathVariable String id) {
        Optional<Book> optional = bookDao.findById(id);
        return optional.get();
    }

    /**
     * @description: 全文搜索
     * @author: wx
     * @date: 2019/3/8 0008
     * @param value
     * @return: java.util.List<com.wx.elasticsearch.elasticsearch.entity.Book>
     */
    @GetMapping("/select")
    public List<Book> testSearch(@RequestParam String value) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(value);
        Iterable<Book> searchResult = bookDao.search(builder);
        Iterator<Book> iterator = searchResult.iterator();
        List<Book> list = new ArrayList<Book>();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }

    /**
     * @description: 新增
     * @author: wx
     * @date: 2019/3/8 0008
     * @param book
     * @return: com.wx.elasticsearch.elasticsearch.entity.Book
     */
    @PostMapping("/insert")
    public Book insertBook(@RequestBody Book book) {
        bookDao.save(book);
        return book;
    }

    /**
     * @description: 删除
     * @author: wx
     * @date: 2019/3/8 0008
     * @param id
     * @return: com.wx.elasticsearch.elasticsearch.entity.Book
     */
    @DeleteMapping("/delete/{id}")
    public Book insertBook(@PathVariable String id) {
        Book book = getBookById(id);
        bookDao.deleteById(id);
        return book;
    }
    
    /**
     * @description: 修改
     * @author: wx
     * @date: 2019/3/8 0008
     * @param book
     * @return: com.wx.elasticsearch.elasticsearch.entity.Book
     */
    @PutMapping("/update")
    public Book updateBook(@RequestBody Book book) {
        bookDao.save(book);
        return book;
    }
}
